import os
import shutil
from classDef import AFFINE_TEST_BASE_PATH
import warnings
import traceback
warnings.filterwarnings("ignore", category=DeprecationWarning)
class visitPCfs:
    def readDoc(self,user, spaceId, docId):
        """
        从本地文件系统的指定空间(spaceId)下读取文件(docId)内容
        """
        docPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docId)
        if os.path.exists(docPath):
            try:
                with open(docPath, "r", encoding="utf-8") as f:
                    content = f.read()
                return {"success": 1, "content": content, "message": "read doc success"}
            except Exception as e:
                traceback.print_exc()
                return {"success": -1, "content": "", "message": f"read doc error: {str(e)}"}
        else:
            return {"success": -1, "content": "", "message": f"doc not found: spaceId={spaceId}, docId={docId}"}

    def updateDoc(self,user, spaceId, docId, content):
        """
        在本地文件系统中更新指定空间(spaceId)下的文件(docId)内容
        updates可包含要写入文件的内容
        """

        docPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docId)
        try:
            # 自动创建空间目录(如不存在)以防止路径错误
            spacePath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId)
            if not os.path.exists(spacePath):
                os.makedirs(spacePath, exist_ok=True)
            with open(docPath, "w", encoding="utf-8") as f:
                f.write(content)
                return {"success": 1, "message": f"update doc success {docId} {content[0:100]}"}
        except Exception as e:
            traceback.print_exc()
            return {"success": -1, "message": f"update doc error: {str(e)}{docId} {content[0:100]}"}
    def createDoc(self,user, spaceId, docName):
        """
        #需要自动在affine后端把user的权限设置为owner
        在本地文件系统中于指定空间(spaceId)下创建新文件(docName)
        """
        docPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docName)
        try:
            # 自动创建空间目录(如不存在)
            spacePath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId)
            if not os.path.exists(spacePath):
                os.makedirs(spacePath, exist_ok=True)
            # 如果文件已存在，直接返回成功或做其他处理
            if os.path.exists(docPath):
                return {"success": -1, "affDocId": docName, "message": "doc already exists"}

            with open(docPath, "w", encoding="utf-8") as f:
                f.write("")  # 默认写入空内容

            return {"success": 1, "affDocId": docName, "message": "create doc success"}
        except Exception as e:
            traceback.print_exc()
            return {"success": -1, "affDocId": docName, "message": f"create doc error: {str(e)}"}

    def createSpace(self,user, spaceName):
        """
        在本地文件系统中创建新空间(目录)
        """
        spacePath = os.path.join(AFFINE_TEST_BASE_PATH, spaceName)
        try:
            if os.path.exists(spacePath):
                return {"success": -1, "affSpaceId": spaceName, "message": "dir already exists"}
            os.makedirs(spacePath)
            return {"success": 1, "affSpaceId": spaceName, "message": "create space success"}
        except Exception as e:
            traceback.print_exc()
            return {"success": -1, "affSpaceId": spaceName, "message": f"create space error: {str(e)}"}

    def renameDoc(self,user, spaceId, docId, newDocName):
        """
        在本地文件系统中重命名指定空间(spaceId)下的文件(docId)为(newDocName)
        """
        oldDocPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docId)
        print(oldDocPath)
        newDocPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, newDocName)
        print(newDocPath)
        try:
            if not os.path.exists(oldDocPath):
                return {"success": -1, "message": "original doc not found, cannot rename"}
            os.rename(oldDocPath, newDocPath)
            return {"success": 1, "message": "rename doc success"}
        except Exception as e:
            traceback.print_exc()
            return {"success": -1, "message": f"rename doc error: {str(e)}"}

    def renameSpace(self,user, spaceId, newSpaceName):
        """
        在本地文件系统中重命名空间(spaceId)为(newSpaceName)
        """
        oldSpacePath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId)
        newSpacePath = os.path.join(AFFINE_TEST_BASE_PATH, newSpaceName)
        try:
            if not os.path.exists(oldSpacePath):
                return {"success": -1, "message": "original space not found, cannot rename"}
            os.rename(oldSpacePath, newSpacePath)
            return {"success": 1, "message": "rename space success"}
        except Exception as e:
            traceback.print_exc()
            return {"success": -1, "message": f"rename space error: {str(e)}"}
   
    def moveDoc(self,user, spaceId, docId, destSpaceId):
        """
        在本地文件系统中将文档(docId)从原空间(spaceId)移动到目标空间(destSpaceId)
        """
        oldDocPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docId)
        newDocDir = os.path.join(AFFINE_TEST_BASE_PATH, destSpaceId)
        newDocPath = os.path.join(newDocDir, docId)
        if not os.path.exists(oldDocPath):
            return {"success": -1, "message": "file not found, cannot move"}
        try:
            if not os.path.exists(newDocDir):
                os.makedirs(newDocDir, exist_ok=True)
            shutil.move(oldDocPath, newDocPath)
            return {"success": 1, "affDocId": f"{docId}", "message": "move doc success"}
        except Exception as e:
            traceback.print_exc()
            error_msg = str(e).replace('\\\\', '\\')
            return {"success": -1, "affDocId": docId, "message": f"move doc error: {error_msg}"}

    def copyDoc(self,user, spaceId, docId, destSpaceId):
        """
        在本地文件系统中将文档(docId)从原空间(spaceId)复制到目标空间(destSpaceId)
        """
        oldDocPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docId)
        newDocDir = os.path.join(AFFINE_TEST_BASE_PATH, destSpaceId)
        newDocPath = os.path.join(newDocDir, docId)

        if not os.path.exists(oldDocPath):
            return {"success": -1, "message": "file not found, cannot copy"}

        try:
            if not os.path.exists(newDocDir):
                os.makedirs(newDocDir, exist_ok=True)
            shutil.copy2(oldDocPath, newDocPath)
            return {"success": 1, "affDocId": f"{docId}", "message": "copy doc success"}
        except Exception as e:
            traceback.print_exc()
            error_msg = str(e).replace('\\\\', '\\')  # 将双反斜杠替换为单反斜杠
            return {"success": -1, "affDocId": docId, "message": f"copy doc error: {error_msg}"}

    def deleteDoc(self,user, spaceId, docId):
        """
        在本地文件系统中删除指定空间(spaceId)下的文件(docId)
        """
        docPath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId, docId)
        if not os.path.exists(docPath):
            return {"success": -1, "message": "doc not found, cannot delete"}
        try:
            if os.path.isdir(docPath):  # 新增目录检查
                return {"success": -1, "message": "path is a directory, use rmdir instead"}
            os.remove(docPath)
            return {"success": 1, "message": "delete doc success"}
        except Exception as e:
            traceback.print_exc()
            # 更明确的错误信息
            return {"success": -1, "message": f"delete doc error: {str(e)}"}

    def deleteSpace(self,user, spaceId):
        """
        在本地文件系统中删除空间(spaceId)及其包含的所有内容(慎用)
        """
        spacePath = os.path.join(AFFINE_TEST_BASE_PATH, spaceId)
        if not os.path.exists(spacePath):
            return {"success": -1, "message": "space not found, cannot delete"}
        try:
            shutil.rmtree(spacePath)
            return {"success": 1, "message": "delete space success"}
        except Exception as e:
            traceback.print_exc()
            return {"success": -1, "message": f"delete space error: {str(e)}"}


def test_visitPCfs():
    # 创建visitPCfs对象
    import os
    v = visitPCfs()

    # 1. 测试createSpace
    test_space = "testSpace"
    result_create_space = v.createSpace(test_space)
    print("测试 createSpace:", result_create_space)

    # 2. 测试createDoc
    test_doc = "testDoc.txt"
    result_create_doc = v.createDoc(test_space, test_doc)
    print("测试 createDoc:", result_create_doc)

    # 3. 测试updateDoc
    updates = {"content": "这是一些测试内容。"}
    result_update_doc = v.updateDoc(test_space, test_doc, updates)
    print("测试 updateDoc:", result_update_doc)

    # 4. 测试readDoc
    result_read_doc = v.readDoc(test_space, test_doc)
    print("测试 readDoc:", result_read_doc)

    # 5. 测试renameDoc
    renamed_doc = "renamedDoc.txt"
    result_rename_doc = v.renameDoc(test_space, test_doc, renamed_doc)
    print("测试 renameDoc:", result_rename_doc)

    # 6. 测试moveDoc (移动到新空间)
    new_space = "testSpace2"
    v.createSpace(new_space)
    result_move_doc = v.moveDoc(test_space, renamed_doc, new_space)
    print("测试 moveDoc:", result_move_doc)

    # 7. 测试copyDoc (复制文件回原空间)
    result_copy_doc = v.copyDoc(new_space, renamed_doc, test_space)
    print("测试 copyDoc:", result_copy_doc)

    # 8. 测试deleteDoc
    # 先删除原空间的文档
    result_delete_doc = v.deleteDoc(test_space, renamed_doc)
    print("测试 deleteDoc:", result_delete_doc)

    # 再删除移动后空间的文档
    result_delete_doc2 = v.deleteDoc(new_space, renamed_doc)
    print("测试 deleteDoc2:", result_delete_doc2)

    # 9. 测试deleteSpace
    # 先删除原空间
    result_delete_space = v.deleteSpace(test_space)
    print("测试 deleteSpace:", result_delete_space)

    # 再删除移动后空间
    result_delete_space2 = v.deleteSpace(new_space)
    print("测试 deleteSpace2:", result_delete_space2)

if __name__ == '__main__':
    test_visitPCfs()

   



